package com.sdp.right.control;

import java.math.BigInteger;
import java.security.MessageDigest;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.threadLocal.ContextManager;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.db.sys_emp.service.ISysEmpService;
import com.sdp.right.entity.SysEmp;
import com.sdp.right.utils.RightConstants;
import com.sdp.right.utils.RsaUtil;

import lombok.extern.slf4j.Slf4j;



@RestController
@RequestMapping("/LoginController")
@Slf4j
public class LoginController {
	
	@Autowired
	private ISysEmpService iSysEmpService;
	
	@Autowired
	private SysLoginLogController sysLoginLogController;
	
	@Autowired
	HttpServletRequest request;
	
	@Value("${sdp.rightMode}")
	private boolean rightMode;
	
	/**
	 * 登录前，先获取密钥
	 * @return
	 */
	@GetMapping(value = "/generateKey")
	public Result<?> generateKey(){
		//生成密钥
		RsaUtil.generateKey();
		return Result.ok(RsaUtil.getpublicKey());
	} 

	
	/**
	 * 登陆
	 * @param sysEmp
	 * DynamicDataSourceContextHolder.push(ds);
	 * @return
	 * @throws Exception 
	 */
	@PostMapping(value = "/login")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> login(@RequestBody SysEmp sysEmp) throws Exception{
		if(sysEmp==null) {
			return Result.error("登录信息为空");
		}
		if(StringUtils.isEmpty(RsaUtil.getprivateKey())) {
			return Result.error("请通过登录页面正常登录");
		}
		
		//对接受的密码进行RSA解密，然后再MD5加密
		String pwd = RsaUtil.decryptByPrivateKey(sysEmp.getEmpPwd(),RsaUtil.getprivateKey());
		
		JSONObject r = new JSONObject();
		r.put("isDefaultPwd", RightConstants.默认密码.getCode().equals(pwd));
		log.info("验证是否为默认密码");
		
		MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(pwd.getBytes());
        sysEmp.setEmpPwd(new BigInteger(1, md.digest()).toString(16));
		BusinessContext businessContext = iSysEmpService.login(sysEmp);
		
		if(businessContext.isSuccess()) {
			RsaUtil.cleanKeyMap();
			//记录登录日志
			sysLoginLogController.addLoginLog(businessContext.get(sysEmp.getClass()));
			r.put("token", businessContext.get("token"));
			return Result.ok(r);
		}else {
			return Result.error(businessContext.getMessage());
		}
	} 
	
	/**
	 * 原来没有RSA加密的登录
	 * @param sysEmp
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/oldLogin")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> oldLogin(@RequestBody SysEmp sysEmp) throws Exception{
		if(sysEmp==null) {
			return Result.error("登录信息为空");
		}
		BusinessContext businessContext = iSysEmpService.login(sysEmp);
		if(businessContext.isSuccess()) {
			//记录登录日志
			sysLoginLogController.addLoginLog(businessContext.get(sysEmp.getClass()));
			return Result.ok(JSONObject.toJSON(businessContext.get("token")));
		}else {
			return Result.error(businessContext.getMessage());
		}
	} 
	
	
	/**
	 * 刷新TOKEN
	 * @return
	 */
	@PostMapping(value = "/refreshToken")
	public Result<?> refreshToken(@RequestBody SysEmp sysEmp) throws Exception{
		String token = request.getHeader(CoreConstantsEnum.header中的token参数名.getCode());
		if(StringUtils.isEmpty(token)) {
			return Result.error("token信息不存在");
		}
		if(StringUtils.isEmpty(sysEmp)) {
			return Result.error("用户信息不存在");
		}
		BusinessContext businessContext = iSysEmpService.login(sysEmp);
		if(businessContext.isSuccess()) {
			return Result.ok(JSONObject.toJSON(businessContext.get("token")));
		}else {
			return Result.error(businessContext.getMessage());
		}
	}
	
	/**
	 * 根据TOKEN获取用户权限信息
	 * @return
	 */
	@GetMapping(value = "/info")
	public Result<?> info(){
		String token = request.getHeader(CoreConstantsEnum.header中的token参数名.getCode());
		String systemNo = ContextManager.getContextData(CoreConstantsEnum.header中的模块参数名.getCode());
		BusinessContext businessContext = iSysEmpService.permissionInfo(rightMode, token, systemNo);
		if(businessContext.isSuccess()) {
			return Result.ok(JSONObject.toJSON(businessContext.get("permissionInfo")));
		}else {
			return Result.error(businessContext.getMessage());
		}
	}
	
}
